/**
 * 主页面JavaScript功能
 * 实现片头选择、模板选择、保存作品等交互功能
 */

// 全局变量
let selectedIntro = null;
let selectedTemplate = null;
let currentUser = null;

// DOM元素
const introItems = document.querySelectorAll('.intro-item');
const templateItems = document.querySelectorAll('.template-item');
const startEditBtn = document.getElementById('start-edit');
const previewBtn = document.getElementById('preview-btn');
const editModal = document.getElementById('edit-modal');
const saveForm = document.getElementById('save-form');
const confirmSaveBtn = document.getElementById('confirm-save');
const cancelSaveBtn = document.getElementById('cancel-save');
const closeModalBtn = document.querySelector('.close');
const usernameDisplay = document.getElementById('username-display');

/**
 * 初始化页面功能
 */
function initializePage() {
    setupIntroSelection();
    setupTemplateSelection();
    setupActionButtons();
    setupModal();
    setupUserManager();
    updateButtonStates();
}

/**
 * 设置片头选择功能
 */
function setupIntroSelection() {
    introItems.forEach(item => {
        item.addEventListener('click', () => {
            // 移除其他选中状态
            introItems.forEach(i => i.classList.remove('selected'));
            // 添加选中状态
            item.classList.add('selected');
            selectedIntro = item.dataset.intro;
            updateButtonStates();
            
            // 添加选择动画效果
            item.style.transform = 'scale(0.95)';
            setTimeout(() => {
                item.style.transform = '';
            }, 150);
        });
    });
}

/**
 * 设置模板选择功能
 */
function setupTemplateSelection() {
    templateItems.forEach(item => {
        item.addEventListener('click', () => {
            // 移除其他选中状态
            templateItems.forEach(i => i.classList.remove('selected'));
            // 添加选中状态
            item.classList.add('selected');
            selectedTemplate = item.dataset.template;
            updateButtonStates();
            
            // 添加选择动画效果
            item.style.transform = 'scale(0.95)';
            setTimeout(() => {
                item.style.transform = '';
            }, 150);
        });
    });
}

/**
 * 设置操作按钮功能
 */
function setupActionButtons() {
    if (startEditBtn) {
        startEditBtn.addEventListener('click', () => {
            if (!selectedIntro || !selectedTemplate) {
                showToast('请先选择片头和模板', 'error');
                return;
            }
            
            if (!currentUser) {
                showToast('请先登录以保存作品', 'error');
                setTimeout(() => {
                    window.location.href = '/profile';
                }, 1500);
                return;
            }
            
            showEditModal();
        });
    }
    
    if (previewBtn) {
        previewBtn.addEventListener('click', () => {
            if (!selectedIntro || !selectedTemplate) {
                showToast('请先选择片头和模板', 'error');
                return;
            }
            
            showPreview();
        });
    }
}

/**
 * 设置模态框功能
 */
function setupModal() {
    if (confirmSaveBtn) {
        confirmSaveBtn.addEventListener('click', saveWork);
    }
    if (cancelSaveBtn) {
        cancelSaveBtn.addEventListener('click', hideEditModal);
    }
    if (closeModalBtn) {
        closeModalBtn.addEventListener('click', hideEditModal);
    }
    
    // 点击模态框外部关闭
    if (editModal) {
        editModal.addEventListener('click', (e) => {
            if (e.target === editModal) {
                hideEditModal();
            }
        });
    }
}

/**
 * 显示编辑模态框
 */
function showEditModal() {
    if (!editModal) return;
    
    const selectedIntroText = getIntroDisplayName(selectedIntro);
    const selectedTemplateText = getTemplateDisplayName(selectedTemplate);
    
    const selectedIntroEl = document.getElementById('selected-intro');
    const selectedTemplateEl = document.getElementById('selected-template');
    const workTitleEl = document.getElementById('work-title');
    
    if (selectedIntroEl) {
        selectedIntroEl.textContent = selectedIntroText;
    }
    if (selectedTemplateEl) {
        selectedTemplateEl.textContent = selectedTemplateText;
    }
    
    editModal.classList.add('show');
    if (workTitleEl) {
        workTitleEl.focus();
    }
}

/**
 * 隐藏编辑模态框
 */
function hideEditModal() {
    if (editModal) {
        editModal.classList.remove('show');
    }
    const workTitleEl = document.getElementById('work-title');
    if (workTitleEl) {
        workTitleEl.value = '';
    }
}

/**
 * 保存作品功能
 */
async function saveWork() {
    const workTitleEl = document.getElementById('work-title');
    if (!workTitleEl) {
        showToast('页面元素未找到', 'error');
        return;
    }
    
    const title = workTitleEl.value.trim();
    
    if (!title) {
        showToast('请输入作品标题', 'error');
        return;
    }
    
    const workData = {
        title: title,
        intro: selectedIntro,
        template: selectedTemplate
    };
    
    try {
        confirmSaveBtn.classList.add('loading');
        confirmSaveBtn.textContent = '保存中...';
        
        const response = await fetch('/api/save-edit', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(workData)
        });
        
        const result = await response.json();
        
        if (result.success) {
            showToast('作品保存成功！', 'success');
            hideEditModal();
            resetSelections();
        } else {
            showToast(result.message || '保存失败', 'error');
        }
    } catch (error) {
        console.error('保存作品失败:', error);
        showToast('网络错误，请重试', 'error');
    } finally {
        confirmSaveBtn.classList.remove('loading');
        confirmSaveBtn.textContent = '保存';
    }
}

/**
 * 显示预览功能
 */
function showPreview() {
    const introText = getIntroDisplayName(selectedIntro);
    const templateText = getTemplateDisplayName(selectedTemplate);
    
    showToast(`预览：${introText} + ${templateText}`, 'success');
    
    // 这里可以添加实际的预览功能
    console.log('预览配置:', {
        intro: selectedIntro,
        template: selectedTemplate
    });
}

/**
 * 重置选择状态
 */
function resetSelections() {
    introItems.forEach(item => item.classList.remove('selected'));
    templateItems.forEach(item => item.classList.remove('selected'));
    selectedIntro = null;
    selectedTemplate = null;
    updateButtonStates();
}

/**
 * 更新按钮状态
 */
function updateButtonStates() {
    const hasSelections = selectedIntro && selectedTemplate;
    
    if (startEditBtn) {
        startEditBtn.disabled = !hasSelections;
    }
    
    if (previewBtn) {
        previewBtn.disabled = !hasSelections;
    }
}

/**
 * 检查用户登录状态
 */
/**
 * 设置用户管理器
 */
function setupUserManager() {
    // 监听用户状态变化
    window.userManager.onUserChange((user) => {
        currentUser = user.isLoggedIn ? user.username : null;
        updateUserDisplay();
    });
    
    // 初始化用户状态
    const user = window.userManager.getCurrentUser();
    currentUser = user.isLoggedIn ? user.username : null;
    updateUserDisplay();
}

/**
 * 更新用户显示
 */
function updateUserDisplay() {
    if (currentUser && usernameDisplay) {
        usernameDisplay.textContent = `欢迎，${currentUser}`;
    } else if (usernameDisplay) {
        usernameDisplay.textContent = '';
    }
}

/**
 * 检查用户状态（保留兼容性）
 */
async function checkUserStatus() {
    const user = await window.userManager.checkStatus();
    currentUser = user.isLoggedIn ? user.username : null;
    updateUserDisplay();
}

/**
 * 获取片头显示名称
 */
function getIntroDisplayName(intro) {
    const names = {
        'modern': '现代风格',
        'classic': '经典风格',
        'dynamic': '动感风格',
        'minimal': '极简风格'
    };
    return names[intro] || intro;
}

/**
 * 获取模板显示名称
 */
function getTemplateDisplayName(template) {
    const names = {
        'vlog': 'Vlog模板',
        'travel': '旅行模板',
        'food': '美食模板',
        'music': '音乐模板'
    };
    return names[template] || template;
}

/**
 * 显示提示消息
 */
function showToast(message, type = 'info') {
    // 移除现有的toast
    const existingToast = document.querySelector('.toast');
    if (existingToast) {
        existingToast.remove();
    }
    
    // 创建新的toast
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.innerHTML = `<span>${message}</span>`;
    
    document.body.appendChild(toast);
    
    // 显示toast
    setTimeout(() => {
        toast.classList.add('show');
    }, 100);
    
    // 自动隐藏toast
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => {
            if (toast.parentNode) {
                toast.parentNode.removeChild(toast);
            }
        }, 300);
    }, 3000);
}

/**
 * 添加触摸反馈效果
 */
function addTouchFeedback() {
    const interactiveElements = document.querySelectorAll('.intro-item, .template-item, .btn, .nav-item');
    
    interactiveElements.forEach(element => {
        element.addEventListener('touchstart', () => {
            element.style.transform = 'scale(0.95)';
        });
        
        element.addEventListener('touchend', () => {
            setTimeout(() => {
                element.style.transform = '';
            }, 150);
        });
    });
}

/**
 * 页面加载完成后初始化
 */
document.addEventListener('DOMContentLoaded', () => {
    initializePage();
    addTouchFeedback();
    
    // 添加页面加载动画
    document.body.classList.add('fade-in');
    

});

/**
 * 处理页面可见性变化
 */
// 页面可见性变化处理已移至userManager

/**
 * 导出功能供其他脚本使用
 */
window.mainPageUtils = {
    showToast,
    checkUserStatus,
    resetSelections
};